package www.openteam.com.ui.prdctnMngmnt;


import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.AppCompatSpinner;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import www.openteam.com.R;
import www.openteam.com.adapter.PrdctnMngmnt.StockTaxAdp;
import www.openteam.com.base.mBaseFragment;
import www.openteam.com.bean.MaxRdsno;
import www.openteam.com.bean.StockTaxLocation;
import www.openteam.com.bean.StockTaxMaterial;
import www.openteam.com.bean.StockTaxSubTable;
import www.openteam.com.bean.UpdateInfo;
import www.openteam.com.contract.PrdctnMngmnt.StockTaxContract;
import www.openteam.com.presenter.prdctnMngmnt.StockTaxPrst;
import www.openteam.com.tool.ToastUtil;
import www.openteam.com.ui.business.ScanActivity;
import www.openteam.com.view.DialogUtil;


/**
 * A simple {@link Fragment} subclass.
 */
public class Stock_TakFragment extends mBaseFragment<StockTaxPrst>
        implements StockTaxContract.StockTaxView {


    @Bind(R.id.stock_tak_add)
    Button stockTakAdd;
    @Bind(R.id.stock_tak_keep)
    Button stockTakKeep;
    private int RESULT_CLASS_CODE = 1;
    @Bind(R.id.stock_tak_location_search)
    AppCompatImageView stockTakLocationSearch;
    @Bind(R.id.stock_tak_location)
    AppCompatSpinner stockTakLocation;
    @Bind(R.id.stock_tak_code)
    TextView stockTakCode;
    @Bind(R.id.stock_tak_class_code_scan)
    AppCompatImageView stockTakClassCodeScan;
    @Bind(R.id.stock_tak_name)
    TextView stockTakName;
    @Bind(R.id.stock_tak_spece)
    TextView stockTakSpece;
    @Bind(R.id.stock_tak_unit)
    TextView stockTakUnit;
    @Bind(R.id.stock_tak_batchNo)
    AppCompatSpinner stockTakBatchNo;
    @Bind(R.id.stock_tak_stockNo)
    EditText stockTakStockCkNum;
    @Bind(R.id.stock_tak_recycleview)
    RecyclerView stockTakRecycleview;
    ArrayAdapter<String> locationAdp;
    private List<StockTaxLocation.DataBeanX.DataBean> dataBeanList;
    private String lcode = "";
    private Intent intent;
    private ArrayList<StockTaxSubTable> stockTaxSubTables;//存放要保存到子表的数据
    private List<StockTaxMaterial.DataBeanX.DataBean> stockTMtrldataBeans;
    private List<StockTaxMaterial.DataBeanX.DataBean> stockTMtrlShowDataBeans;    //存放显示的数据
    private StockTaxAdp stockTaxAdp;
    private int ismodify = 0;//是否是选择的列表的数据0为否，1为是
    private String year;
    private String month;
    private String moreCom;
    private String prefix;
    private String link = "OP";
    private int length = 5;
    private String rdsno;
    private DialogUtil dialogUtil;

    public Stock_TakFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_stock__tak, container, false);
        ButterKnife.bind(this, view);
        mPresenter = loadPresenter();
        initData();
        initView();
        initListener();
        return view;
    }

    @Override
    protected void initData() {
        if (mPresenter != null)
            mPresenter.attachView(this);
        intent = new Intent(getActivity(), ScanActivity.class);
        mProgressDialog = new ProgressDialog(getContext());
        stockTaxSubTables = new ArrayList<>();
        stockTMtrlShowDataBeans = new ArrayList<>();
        stockTaxAdp = new StockTaxAdp(getContext());
        linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setStackFromEnd(true);//列表再底部开始展示，反转后由上面开始展示
        linearLayoutManager.setReverseLayout(true);//列表翻转
        stockTakRecycleview.setLayoutManager(linearLayoutManager);
        Calendar cal = Calendar.getInstance();
        year = String.format("%02d", cal.get(Calendar.YEAR)).substring(2, 4);
        month = String.format("%02d", cal.get(Calendar.MONTH) + 1);
        moreCom = mySetting.getString("rMoreCom", "");
        prefix = mySetting.getString("rPrefix", "");
        dialogUtil = new DialogUtil();
    }

    @Override
    protected void initListener() {
        //库位数据查询
        stockTakLocationSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mProgressDialog.show();
                mPresenter.findLocation();
                //同时查询maxRdsno
                mPresenter.findMaxRdsno("stCheckStock", moreCom, prefix, link, year, month);
            }
        });
        //分类编号扫描
        stockTakClassCodeScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ("" == lcode) {
                    ToastUtil.showToast(getContext(), "请先进行库位选择");
                    return;
                }
//                startActivityForResult(intent, RESULT_CLASS_CODE);
                mPresenter.findDataFromClassCode("10001-10sp001", lcode);
                mProgressDialog.show();
            }
        });

        //添加操作
        stockTakAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int itemPostion = stockTakBatchNo.getSelectedItemPosition();
                StockTaxMaterial.DataBeanX.DataBean dataBean = stockTMtrldataBeans.get(itemPostion);
                StockTaxSubTable stockTaxSubTable = new StockTaxSubTable();
                stockTaxSubTable.setBatchNo(dataBean.getBatchNo());
                stockTaxSubTable.setCode(dataBean.getCode());
//                stockTaxSubTable.setInputDate(simpleDateFormat.format(date));
                stockTaxSubTable.setLocation(lcode);
                stockTaxSubTable.setPrice(dataBean.getSumPirce());
                stockTaxSubTable.setStnumb(dataBean.getNumb());
                String stype = mySetting.getString("rCode", "");
                stockTaxSubTable.setStype(stype);
                stockTaxSubTable.setType(dataBean.getType());

                int ckNumb = stringToInt(stockTakStockCkNum.getText().toString());
                int size = stockTMtrlShowDataBeans.size();
//                stockTaxSubTable.setCknumb(ckNumb);
//                dataBean.setCknumb(ckNumb);
                int status = 0;
                int modifPostion = -1;
                if (ismodify == 1) {
                    //ismodify判断是否是下方列表的选择项,为1表示是,status设置为1，表示需要修改
                    status = 1;
                    modifPostion = itemPostion;
                } else {
                    //否则表示为扫描数据
                    for (int i = 0; i < size; i++) {
                        if (stockTMtrlShowDataBeans.size() > 0
                                && dataBean.getBatchNo().equals(stockTMtrlShowDataBeans.get(i).getBatchNo())) {
                            //扫描判断。如果下方列表中已存在此时扫描的批次,进行修改已存在的ckNumb+输入框的ck，否则添加
                            //自动生成批次的问题
                            ckNumb = stockTMtrlShowDataBeans.get(i).getCknumb() + ckNumb;
                            status = 1;
                            modifPostion = i;
                            break;
                        }
                    }
                }
                stockTaxSubTable.setCknumb(ckNumb);
                dataBean.setCknumb(ckNumb);
                if (status == 0) {
                    //不需要修改
                    stockTaxSubTables.add(stockTaxSubTable);
                    stockTMtrlShowDataBeans.add(dataBean);
                } else if (status == 1) {
                    //需要修改
                    stockTaxSubTables.set(modifPostion, stockTaxSubTable);
                    stockTMtrlShowDataBeans.set(modifPostion, dataBean);
                }
                if (stockTaxAdp.getItemCount() == 0) {
                    stockTaxAdp.setmSortedList(stockTMtrlShowDataBeans);
                    stockTakRecycleview.setAdapter(stockTaxAdp);
                    stockTaxAdp.notifyDataSetChanged();
                } else {
                    if (status == 1) {
                        stockTaxAdp.setItem(modifPostion, dataBean);
                    } else if (status == 0) {
                        stockTaxAdp.addItem(dataBean);
                    }
                }
            }
        });
        stockTaxAdp.setStockTaxSelectAdpClick(new StockTaxAdp.StockTaxAdpSelectkClick() {
            @Override
            public void selection(int postion) {
                StockTaxMaterial.DataBeanX.DataBean dataBean = stockTMtrlShowDataBeans.get(postion);
                stockTakCode.setText(dataBean.getCode());
                stockTakName.setText(dataBean.getName());
                stockTakSpece.setText(dataBean.getSpecs());
                stockTakUnit.setText(dataBean.getUnit());
                stockTakStockCkNum.setText(dataBean.getCknumb() + "");
                ismodify = 1;

            }
        });
        stockTakKeep.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialogUtil.show(getContext(), "保存后此处不能修改，是否确定保存", new DialogUtil.DialogButtonListener() {
                    @Override
                    public void sure() {
                        Gson gson = new Gson();
                        try {
                            String stCheckLst = gson.toJson(stockTaxSubTables);
                            stCheckLst = URLEncoder.encode(stCheckLst, "UTF-8");
                            String inputer = mySetting.getString("mName","");
                            int mid = mySetting.getInt("mId",0);
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// HH:mm:ss
                            //获取当前时间
                            Date date = new Date(System.currentTimeMillis());
                            String inputerDate = simpleDateFormat.format(date);
                            mPresenter.insertStCheckStock(stCheckLst,inputer,moreCom,mid+"",inputerDate);
                            mProgressDialog.show();
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
//                        mPresenter.unaudit(zbid);
                        mProgressDialog.show();
                    }

                    @Override
                    public void cancel() {
                    }
                });

            }
        });
    }

    public int stringToInt(String s) {
        return Integer.valueOf(s);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        String class_code = data.getStringExtra("work_order_id");
        if (requestCode == RESULT_CLASS_CODE && !class_code.equals("")) {
            mPresenter.findDataFromClassCode(class_code, lcode);

            mProgressDialog.show();
        }
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void otherViewClick(View view) {

    }

    @Override
    protected StockTaxPrst loadPresenter() {
        return new StockTaxPrst();
    }

    @Override
    public void onRefresh() {

    }


    @Override
    public void findDataFromClassCode(StockTaxMaterial stockTaxMaterial) {
        mProgressDialog.cancel();
        if (null == stockTaxMaterial.getData()) {
            ToastUtil.showToast(getContext(), stockTaxMaterial.getInfo());
            return;
        }
        stockTMtrldataBeans = stockTaxMaterial.getData().getData();
        final ArrayList<String> batchNoList = new ArrayList<String>();
        int size = stockTMtrldataBeans.size();
        for (int i = 0; i < size; i++) {
            StockTaxMaterial.DataBeanX.DataBean dataBean = stockTMtrldataBeans.get(i);
            if (null == dataBean.getBatchNo() || "".equals(dataBean.getBatchNo())) {
                //生成一个入库批号+行号
                String targetRdsno = "";
                if ("".equals(rdsno) || null == rdsno) {
                    targetRdsno = moreCom + prefix + "OP" + year + month + String.format("%0" + length + "d", 1);
                } else {
                    String subRdsno = rdsno.substring(0, prefix.length() + moreCom.length() + link.length() + 4);
                    targetRdsno = subRdsno + String.format("%0" + length + "d", (Integer.parseInt(
                            rdsno.substring(subRdsno.length(), rdsno.length())) + 1));
                }
                int row = 1;
                //取得行号，判断存储显示数据的集合
                if (null != stockTMtrlShowDataBeans) {
                    row = 1 + stockTMtrlShowDataBeans.size();
                }
                dataBean.setBatchNo(targetRdsno +"-"+ row);
            }
            batchNoList.add(dataBean.getBatchNo());
        }
        ArrayAdapter<String> batchNoAdp = new ArrayAdapter<>(getContext(),
                android.R.layout.simple_spinner_dropdown_item, batchNoList);
        stockTakBatchNo.setAdapter(batchNoAdp);
        stockTakBatchNo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                StockTaxMaterial.DataBeanX.DataBean dataBean = stockTMtrldataBeans.get(i);
                stockTakCode.setText(dataBean.getCode());
                stockTakName.setText(dataBean.getName());
                stockTakSpece.setText(dataBean.getSpecs());
                stockTakUnit.setText(dataBean.getUnit());
                stockTakStockCkNum.setText(dataBean.getCknumb() + "");
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

    }

    @Override
    public void findDataFromClassCodeFail(String error) {
        mProgressDialog.cancel();
        ToastUtil.showToast(getContext(), error);
    }

    @Override
    public void findLocation(StockTaxLocation stockTaxLocation) {
        mProgressDialog.cancel();
        if (null == stockTaxLocation.getData() || "".equals(stockTaxLocation.getData())) {
            ToastUtil.showToast(getContext(), stockTaxLocation.getInfo());
            return;
        }
        dataBeanList = stockTaxLocation.getData().getData();
        ArrayList<String> locationList = new ArrayList<>();
        for (StockTaxLocation.DataBeanX.DataBean dataBean : dataBeanList) {
            locationList.add(dataBean.getLocation());
        }
        locationAdp = new ArrayAdapter<String>(getContext(),
                android.R.layout.simple_spinner_dropdown_item, locationList);
        stockTakLocation.setAdapter(locationAdp);
        //对库位选择进行监听得到库位编号
        stockTakLocation.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                lcode = dataBeanList.get(i).getCode();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    @Override
    public void findLocationFail(String error) {
        mProgressDialog.cancel();
        ToastUtil.showToast(getContext(), error);
    }

    @Override
    public void findMaxRdsno(MaxRdsno maxRdsno) {
        mProgressDialog.cancel();
        if (null == maxRdsno.getData() || "".equals(maxRdsno.getData())) {
            rdsno = "";
        } else {
            rdsno = maxRdsno.getData().getData().get(0).getMaxRdsno();
        }

    }

    @Override
    public void findMaxRdsnoFail(String error) {
        mProgressDialog.cancel();
        ToastUtil.showToast(getContext(), error);
    }

    @Override
    public void insertStCkStkSucess(UpdateInfo info) {
        mProgressDialog.cancel();
        ToastUtil.showToast(getContext(),info.getInfo());
    }

    @Override
    public void insertStCkStkFail(String error) {
        mProgressDialog.cancel();
        ToastUtil.showToast(getContext(),error);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
